package com.briup.cms.web.interceptor;

import com.auth0.jwt.exceptions.JWTVerificationException;
import com.briup.cms.exception.CustomerException;
import com.briup.cms.utils.JwtUtil;
import com.briup.cms.utils.MessageStatus;
import com.briup.cms.utils.UserInfo;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @Description 拦截器类
 * @Author lining
 * @Date 2021/7/16 17:19
 * @Version 1.0.0
 */
public class JwtInterceptor implements HandlerInterceptor {
    //1.需要在每次请求前拦截请求信息，获取token值，进行验证
    // localhost:8080/auth/index.html
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截到请求:"+request.getRequestURI());
        //如果请求的静态资源，通过验证
        if(!(handler instanceof HandlerMethod)){
            return true;
        }

        // return false;//拦截成功， 无法继续执行请求
        //1.通过请求信息获取token字符串 : 请求头信息
        String token = request.getHeader("Authorization");
        //2.但token不存在
        if(token == null){
           throw new CustomerException(MessageStatus.USER_TOKEN_NOT_EXIST);
        }
        //3.token值存在，但是是无效的token : 假冒  过期
        try {
            JwtUtil.checkSign(token);
        } catch (JWTVerificationException e) {
           throw new  CustomerException(MessageStatus.USER_TOKEN_INVALID);
        }
        //日志功能： 通过request对象获取url 和method,
        String uri = request.getRequestURI();
        String method = request.getMethod();
        Map<String, Object> userInfo = JwtUtil.getInfo(token);

        userInfo.put("uri",uri);
        userInfo.put("method",method);
        //用户信息保存在ThreadLocal对象中
        UserInfo.setUserinfo(userInfo);



        //4.token认证通过，继续请求的url
        return true;
    }
}
